package controller

import (
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
    "generator-tool/models"
    "generator-tool/service"
)

type ShGoodsCategoryController struct {
    Service *service.ShGoodsCategoryService
}

func NewShGoodsCategoryController(service *service.ShGoodsCategoryService) *ShGoodsCategoryController {
    return &ShGoodsCategoryController{Service: service}
}

func (ctl *ShGoodsCategoryController) Create(c *gin.Context) {
    var ShGoodsCategory models.ShGoodsCategory
    if err := c.ShouldBindJSON(&ShGoodsCategory); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := ctl.Service.CreateShGoodsCategory(&ShGoodsCategory); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusCreated, gin.H{"data": ShGoodsCategory})
}

func (ctl *ShGoodsCategoryController) GetAll(c *gin.Context) {
    ShGoodsCategorys, err := ctl.Service.GetAllShGoodsCategorys()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, gin.H{"data": ShGoodsCategorys})
}

func (ctl *ShGoodsCategoryController) GetByID(c *gin.Context) {
    id, err := strconv.ParseUint(c.Param("id"), 10, 32)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
        return
    }

    ShGoodsCategory, err := ctl.Service.GetShGoodsCategoryByID(uint(id))
    if err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"data": ShGoodsCategory})
}

func (ctl *ShGoodsCategoryController) Update(c *gin.Context) {
    id, err := strconv.ParseUint(c.Param("id"), 10, 32)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
        return
    }

    var ShGoodsCategory models.ShGoodsCategory
    if err := c.ShouldBindJSON(&ShGoodsCategory); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := ctl.Service.UpdateShGoodsCategory(uint(id), &ShGoodsCategory); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"message": "updated successfully"})
}

func (ctl *ShGoodsCategoryController) Delete(c *gin.Context) {
    id, err := strconv.ParseUint(c.Param("id"), 10, 32)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
        return
    }

    if err := ctl.Service.DeleteShGoodsCategory(uint(id)); err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"message": "deleted successfully"})
}